<script setup lang="ts">
import { onHide, onShow } from '@dcloudio/uni-app';
import { watchPausable } from '@vueuse/shared';
import { storeToRefs } from 'pinia';
import { computed } from 'vue';
import { useCountdown } from '@/hooks/useCountdown';
import { useUserStore } from '@/store/userStore';
import { IS_DEV } from '@/utils';
import { isEmpty } from '@/utils/is.utils';
import { maskName } from '@/utils/mask.utils';

const props = withDefaults(defineProps<{
  countdown?: number
}>(), {
  countdown: 120
});

const emit = defineEmits<{
  login: []
}>();

const { remaining, start, stop } = useCountdown(props.countdown, {
  onComplete() {
    if (!IS_DEV) {
      userStore.resetAuth();
    }
    console.log('>>>>倒计时结束');
  }
});

const userStore = useUserStore();

const { authStore, userInfo } = storeToRefs(userStore);

// 患者信息
const patientInfo = computed(() => !isEmpty(authStore.value.accessToken) && !isEmpty(userInfo.value));

// 前往登录
function handleLogin() {
  emit('login');
}

// 退出登录
function handleLogout() {
  userStore.handleLogout().then(() => {
    stop();
  });
}

function toggleCountdown() {
  if (patientInfo.value) {
    start();
  }
  else {
    stop();
  }
}

const {
  resume: watchPatientInfo,
  stop: unwatchPatientInfo
} = watchPausable(patientInfo, toggleCountdown, {
  immediate: true
});

onShow(() => {
  toggleCountdown();
  watchPatientInfo();
});

onHide(() => {
  stop();
  unwatchPatientInfo();
});
</script>

<template>
  <view class="auth-bar flex items-center justify-between">
    <view class="auth-bar__left w-220" />
    <view class="auth-bar__center">
      <!-- 未登录 -->
      <view v-if="!patientInfo" class="flex items-center">
        <view class="auth-bar__title">
          请登录您的账号
        </view>
        <view class="auth-bar__btn" @click="handleLogin">
          登录
        </view>
      </view>
      <!-- 已登录 -->
      <view v-else class="flex items-center">
        <view class="auth-bar__title">
          欢迎您,{{ maskName(userInfo.patientName) }}！
        </view>
        <view class="auth-bar__btn" @click="handleLogout">
          退出
        </view>
      </view>
    </view>
    <view class="auth-bar__right w-220">
      <view v-if="patientInfo" class="auth-bar__time">
        {{ remaining }}秒后自动退出
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.auth-bar {
  padding: 22px;
  .auth-bar__title {
    font-size: 36px;
    font-weight: bold;

    color: var(--text-color);
  }
  .auth-bar__btn {
    background: rgba(247, 250, 254, 0.5);
    border-radius: 100px;
    width: 115px;
    height: 44px;
    color: var(--primary);
    box-sizing: border-box;
    font-size: 26px;
    font-weight: 500;
    border: 2px solid rgba(255, 255, 255, 0.5);
    text-align: center;
    margin-left: 24px;
  }

  .auth-bar__time {
    font-size: 28px;
    color: var(--text-color);
  }
}
</style>
